package com.atguigu.myjuc.cas;

import java.sql.Time;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 100个线程，每个线程加100次，求最后的number值
 */
class cas{
    private int number;

    //------------------------------------------//老版本v1------------------------
    //读，不用加
    public int getNumber() {
        return number;
    }

    //写操作，加上锁
    public synchronized void setNumber() {
        ++number;
    }

    //------------------------------------------//新版本v2------------------------
    //cas
    AtomicInteger atomicInteger = new AtomicInteger();

    //读方法
    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    //这里还是写方法，不用加锁，因为天生原子性
    public void setAtomicInteger() {
        atomicInteger.incrementAndGet();//++i
    }

}



public class CASDemo {
    public static void main(String[] args) throws InterruptedException {

        cas cas = new cas();
        CountDownLatch countDownLatch = new CountDownLatch(100);//juc强大辅助类

        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                for (int j = 0; j < 100; j++) {
                    cas.setNumber();
                    cas.setAtomicInteger();
                }
                countDownLatch.countDown(); // 每调用一次，计数减一
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t"+"获得最后结果： "+cas.getNumber());
        System.out.println(Thread.currentThread().getName()+"\t"+"获得最后结果： "+cas.getAtomicInteger().get());

    }

}
